package com.aku.service.impl;

import com.aku.exception.AddFailException;
import com.aku.mapper.BorrowMapper;
import com.aku.mapper.StudentMapper;
import com.aku.mapper.UserMapper;
import com.aku.pojo.Student;
import com.aku.pojo.User;
import com.aku.service.StudentService;
import com.aku.vo.RegisterStudent;
import com.aku.vo.ShowBorrow;
import com.aku.vo.ShowStudent;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    private PasswordEncoder encoder = new BCryptPasswordEncoder();

    @Resource
    private UserMapper userMapper;
    @Resource
    private StudentMapper studentMapper;
    @Resource
    private BorrowMapper borrowMapper;

    /**
     * 前端接收到一个用户注册的信息
     * 对应数据库添加的数据:
     *      用户表 : username(用户账号) , password(用户密码)
     *      学生表 : uid(用户id) , name(学生姓名) , sex(学生性别) , grade(学生年级)
     * @param registerStudent 前端用户信息
     * @return boolean?添加成功:添加失败
     */
    @Override
    @Transactional
    public boolean insertStudent(RegisterStudent registerStudent) {
        User user = new User(null, registerStudent.getUsername(),
                encoder.encode(registerStudent.getPassword()), null);
        int isInsertUser = userMapper.insertUser(user);
        if (!(isInsertUser > 0)) {
            throw new AddFailException("注册失败");
        }
        Student student = new Student(null, user.getId(), registerStudent.getName(), registerStudent.getSex(), registerStudent.getGrade());
        int isInsertStudent = studentMapper.insertStudent(student);

        return isInsertStudent > 0;
    }

    @Override
    public List<ShowStudent> searchStudentsBorrow() {
        List<Student> students = studentMapper.selectAllStudent();
        List<ShowStudent> showStudentList = new ArrayList<>();
        for(Student student : students){
            String username = userMapper.selectUsernameByUid(student.getUid());
            int studentBorNum = borrowMapper.selectBorrowNumBySid(student.getSid());
            ShowStudent showStudent = new ShowStudent(student.getSid(),username, student.getName(), student.getSex(), student.getGrade(), studentBorNum);
            showStudentList.add(showStudent);
        }
        return showStudentList;
    }


}
